package com.zty.xiaomi.server.WebSocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zty.xiaomi.server.Entity.Message.message;
import com.zty.xiaomi.server.Entity.Message.orderMessage;
import com.zty.xiaomi.server.utils.SpringbootUntil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.EOFException;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/webSocket/{userId}")
@Component
public class WebSocketServer {

    private static ConcurrentHashMap sessionPoil = new ConcurrentHashMap();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) throws InterruptedException {

        if (sessionPoil.get(userId) != null) {
            System.out.println("已经成功加入");
            this.send(userId, "已经成功加入");
            return;
        }
        sessionPoil.put(userId, session);
//        for (int i = 0; i < 10; i++) {
//
//            Thread.sleep(5000);
//            this.send(userId, "第" + i + "次发送");
//        }

//		for(int i=0;i<100;i++) {
//			Thread.sleep(1000);
//			this.send("服务端推送："+i);
//		}
    }

    @OnClose
    public void onClose(@PathParam(value = "userId") String userId) throws EOFException {
        System.out.println(userId);
        sessionPoil.remove(userId);
        System.out.println("用户下线");
//		this.send("有用户离开");
    }

    @OnMessage
    public void onMessage(String msg) throws InterruptedException {
        message message = JSONObject.parseObject(msg, message.class);
        if(message.getIdentity().contains("order")){
          orderMessage orderMessage=JSONObject.parseObject(msg, com.zty.xiaomi.server.Entity.Message.orderMessage.class);
            System.out.println(orderMessage);
          redisStorageOrder(orderMessage);
          return;
        }
        redisStorage(message);
        this.send(message.getTo(), message.getMsg());
        System.out.println("从客服端接受的消息： " + msg);
    }

    @OnError
    public void onError(Throwable error) {

        System.out.println("客户端掉线");
    }


    public void send(String userId, String msg) {

        Session session = (Session) sessionPoil.get(userId);

        try {
            if (session != null) {
                session.getBasicRemote().sendText(msg);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void redisStorage(message message) {
        RedisTemplate redisTemplate = (RedisTemplate) SpringbootUntil.getBean("redisTemplate");
        if (message.getIdentity().equals("service")){
            String key = message.getTo() + '&' + message.getUsername();
            redisTemplate.opsForList().rightPush(key, message);
            return;
        }
        String key = message.getUsername() + '&' + message.getTo();
        redisTemplate.opsForHash().put(message.getTo(),message.getUsername(),message.getMsg());
        redisTemplate.opsForList().rightPush(key, message);

    }
    public void redisStorageOrder(orderMessage message) {
        RedisTemplate redisTemplate = (RedisTemplate) SpringbootUntil.getBean("redisTemplate");
        String key = message.getUsername() + '&' + message.getTo();
        redisTemplate.opsForHash().put(message.getTo(),message.getUsername(),message.getMsg());
        redisTemplate.opsForList().rightPush(key, message);


    }

}
